import { Module } from "vuex";
import { ILoginState } from "./types";
import { IRootState } from "../types";

import LocalCache from "@/utils/cache";
import router from "@/router";
import { useStore } from "vuex";

import { mapMenusToRoutes, mapMenusToPermissions } from "@/utils/map-menus";

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId,
} from "@/service/login/login";

// 这里需要两个类型C参数 第一个是本模块中的类型，第二个是根模块里面的类型
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true, //模块一般都需要给命名空间
  state() {
    return {
      token: "",
      userInfo: {},
      userMenus: [],
      permissions: [],
    };
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token;
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    saveUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;
      const routes = mapMenusToRoutes(userMenus); //得到权限内的所有路由
      // 遍历添加路由到 main 下面。
      routes.forEach((route) => {
        router.addRoute("main", route);
      });

      // 获取用户按钮权限
      const permissions = mapMenusToPermissions(userMenus);
      state.permissions = permissions;
    },
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: any) {
      console.log("accountLoginAction", payload);
      // 1、实现登录逻辑
      const loginResult = await accountLoginRequest(payload);
      console.log(loginResult);
      const { id, token } = loginResult.data;
      commit("saveToken", token);
      LocalCache.setCache("token", token); //将token保存到本地 在请求拦截里面读取使用
      // 2、请求用户信息
      const userInfoRequest = await requestUserInfoById(id);
      const userInfo = userInfoRequest.data;
      console.log(userInfo);
      commit("saveUserInfo", userInfo); //保存信息
      LocalCache.setCache("userInfo", userInfo); //缓存用户详情
      // 3、请求用户菜单
      const userMenusRequest = await requestUserMenusByRoleId(userInfo.role.id);
      const userMenus = userMenusRequest.data;
      console.log("userMenus=>", userMenus);
      commit("saveUserMenus", userMenus);
      LocalCache.setCache("userMenus", userMenus); //缓存用户菜单栏详情

      // 3.5、请求部门和角色数据动态插入options
      dispatch("getInitialDataAction", null, { root: true });
      // 4、跳转到首页
      router.push("/main");
    },
    // 对应刷新操作
    loadLocalLogin({ commit, dispatch }) {
      const token = LocalCache.getCache("token");
      if (token) {
        commit("saveToken", token);
        // 3.5、请求部门和角色数据动态插入options(因为发送请求需要用到token)
        dispatch("getInitialDataAction", null, { root: true });
      }

      const userInfo = LocalCache.getCache("userInfo");
      if (userInfo) {
        commit("saveUserInfo", userInfo);
      }
      const userMenus = LocalCache.getCache("userMenus");
      if (userMenus) {
        commit("saveUserMenus", userMenus);
      }
    },
  },
};

export default loginModule;
